package com.example.webserver.server;

import com.example.webserver.client.GreetingService;
import com.example.webserver.shared.FieldVerifier;
import com.example.webservice.ExampleImpl;
import com.example.webservice.ExampleImplService;
import com.example.webservice.Fullname;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements
	GreetingService
{

    public String greetServer(String input) throws IllegalArgumentException
    {
	// Verify that the input is valid. 
	if (!FieldVerifier.isValidName(input))
	{
	    // If the input is not valid, throw an IllegalArgumentException back to
	    // the client.
	    throw new IllegalArgumentException(
		    "Name must be at least 4 characters long");
	}

	String serverInfo = getServletContext().getServerInfo();
	String userAgent = getThreadLocalRequest().getHeader("User-Agent");

	// Escape data from the client to avoid cross-site script vulnerabilities.
	input = escapeHtml(input);
	userAgent = escapeHtml(userAgent);
	
	/*
	 * Call ExampleService webservice
	 */
	String welcome = "error";
	Fullname response = new Fullname();
	response.setFirstname("Wrong");
	response.setLastname("Name");
	Fullname request = new Fullname();
	request.setFirstname("Tamás");
	request.setLastname("Bátya");
	System.out.println("Trying to call Example");
	try {
	    ExampleImplService service = new ExampleImplService();
	    ExampleImpl example = service.getExampleImplPort();
	    
	    welcome = example.getWelcome(input);
	    response = example.getFullname(request);
	    
        }
	catch (Exception ex)
	{
	    System.out.println(ex.getMessage());
	}
	
	return String.format("%s<br/><br/>%s, %s",  welcome, response.getLastname(), response.getFirstname());
	
	//return "Hello, " + input + "!<br><br>I am running " + serverInfo
	//	+ ".<br><br>It looks like you are using:<br>" + userAgent;
    }

    /**
     * Escape an html string. Escaping data received from the client helps to
     * prevent cross-site script vulnerabilities.
     * 
     * @param html the html string to escape
     * @return the escaped string
     */
    private String escapeHtml(String html)
    {
	if (html == null)
	{
	    return null;
	}
	return html.replaceAll("&", "&amp;").replaceAll("<", "&lt;")
		.replaceAll(">", "&gt;");
    }
}
